import { Input, InputNumber } from '@/components/AntdProxy';
import { TRIP_STATE_MAP } from '@/constants/enums';
import request from '@/utils/request';
import { SettingOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { Button, Col, Form, Popover, Row, Select, Space, Table } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
const VehicleDriverTable = (props) => {
  const { value = [], onChange, groupId, lineId } = props;
  const [form] = Form.useForm();
  const dataMap = useRef({});
  const [search, setSearch] = useState('');
  const { data, loading, runAsync } = useRequest(
    async (params) => {
      const res = await request({
        url: '/datas/trip/realtime/vehicle/bind/list',
        method: 'GET',
        params,
      });
      dataMap.current = res?.reduce((acc, item) => {
        acc[item.vehicleId] = item;
        return acc;
      }, {});
      return res;
    },
    {
      manual: true,
    },
  );
  const { data: driverData, runAsync: runDriverAsync } = useRequest(
    async (params) =>
      request({
        url: '/base/driver/list',
        method: 'GET',
        params,
      }),
    {
      manual: true,
    },
  );

  useEffect(() => {
    if (groupId) {
      runAsync({ groupId, lineId });
      runDriverAsync({ index: 0, size: 0 });
    }
  }, [groupId, lineId]);

  const handleBatchSet = () => {
    const total = form.getFieldValue('total');
    const newData = [...value];
    newData.forEach((item) => {
      item.total = total;
    });
    onChange?.(newData);
  };
  const leftColumns = [
    {
      title: '线路',
      dataIndex: 'lineName',
      width: 280,
      ellipsis: true,
    },
    {
      title: '车牌号',
      dataIndex: 'license',
      width: 120,
      ellipsis: true,
    },
    {
      title: '司机',
      dataIndex: 'realname',
      width: 100,
      ellipsis: true,
    },
    {
      title: '装货地距离(km)',
      dataIndex: 'distance',
      width: 140,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'state',
      width: 100,
      ellipsis: true,
      render: (text) => TRIP_STATE_MAP[text],
    },
  ];
  const rightColumns = [
    {
      title: '车牌号',
      dataIndex: 'license',
      width: 120,
    },
    {
      title: '司机',
      dataIndex: 'driverId',
      width: 150,
      render: (text, record, index) => {
        return (
          <Select
            value={text ? text : undefined}
            options={driverData}
            style={{ width: '100%' }}
            size="small"
            fieldNames={{ label: 'realname', value: 'driverId' }}
            placeholder="请选择司机"
            allowClear
            showSearch
            filterOption={(input, option) =>
              option.realname.toLowerCase().includes(input.toLowerCase())
            }
            onChange={(_value, _option) => {
              // 替换当前位置的数据
              const newData = [...value];
              newData[index] = {
                ...record,
                driverId: _value,
                telephone: _option?.phone,
              };
              onChange(newData);
            }}
          />
        );
      },
    },
    {
      title: '手机号',
      dataIndex: 'telephone',
      width: 130,
    },
    {
      title: (
        <Space>
          数量
          <Popover
            title="批量设置"
            content={
              <Form form={form}>
                <Form.Item name="total">
                  <InputNumber size="small" placeholder="请输入" />
                </Form.Item>
                <Button size="small" type="primary" onClick={handleBatchSet}>
                  确定
                </Button>
              </Form>
            }
          >
            <SettingOutlined style={{ cursor: 'pointer' }} />
          </Popover>
        </Space>
      ),
      dataIndex: 'total',
      width: 110,
      render: (text, record, index) => {
        return (
          <InputNumber
            min={1}
            size="small"
            style={{ width: '100%' }}
            value={text || 1}
            onChange={(_value, _option) => {
              // 替换当前位置的数据
              const newData = [...value];
              newData[index] = {
                ...record,
                total: _value,
              };
              onChange(newData);
            }}
          />
        );
      },
    },
  ];

  const selectedRowKeys = useMemo(
    () => value.map((item) => item.vehicleId),
    [value],
  );

  const filteredData = useMemo(() => {
    if (!search) {
      return data;
    }
    return data.filter((item) => item.license?.includes(search));
  }, [data, search]);
  return (
    <Row>
      <Col span={12}>
        <Table
          title={() => (
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <div style={{ fontWeight: 'bold' }}>待选项</div>
              <div>
                车牌号:
                <Input.Search
                  allowClear
                  size="small"
                  placeholder="请输入车牌号搜索"
                  style={{ width: 180, marginLeft: 8 }}
                  onSearch={(_value) => setSearch(_value)}
                  onClear={() => setSearch('')}
                  onChange={(e) => !e.target.value && setSearch('')}
                />
              </div>
            </div>
          )}
          bordered
          loading={loading}
          columns={leftColumns}
          dataSource={filteredData}
          pagination={false}
          rowKey="vehicleId"
          virtual
          scroll={{ y: 300 }}
          rowSelection={{
            preserveSelectedRowKeys: true,
            selectedRowKeys,
            columnWidth: 40,
            fixed: 'left',
            onChange: (_selectedRowKeys) => {
              const result = _selectedRowKeys.map((key) => {
                const rightTarget = value.find(
                  (item) => item.vehicleId === key,
                );
                if (rightTarget) {
                  return rightTarget;
                }
                return dataMap.current[key];
              });
              onChange(result);
            },
          }}
        />
      </Col>
      <Col span={11} offset={1}>
        <Table
          title={() => <div>已选项</div>}
          bordered
          columns={rightColumns}
          dataSource={value}
          pagination={false}
          rowKey="vehicleId"
          virtual
          scroll={{ y: 300 }}
        />
      </Col>
    </Row>
  );
};

export default VehicleDriverTable;
